﻿using XfTechOAWeb.Data;
using XfTechOAWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Dtos;

using Microsoft.EntityFrameworkCore; //应用ef core的命名空间
using System.Data;
using XfTechOAWeb.EFCore.Base;

namespace XfTechOAWeb.EFCore
{
    public class RoleRepository: EfBaseRepository<Role>, IRoleRepository
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">上下文注入</param>
        public RoleRepository(DbContext db) : base(db)
        {
            _db = db;
        }

        /// <summary>
        /// 获取角色的所有权限
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public List<RolePermission> GetRolePermissions(int rid)
        {
            var list = _db.Set<RolePermission>().Where(x => x.RoleId == rid).ToList();
            return list;
        }

        /// <summary>
        /// 给角色添加权限
        /// </summary>
        /// <param name="rid"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public int AddRolePermission(int rid, string pid)
        {
            //先删除原有的权限
            var list = _db.Set<RolePermission>().Where(x => x.RoleId == rid).ToList();
            if (list != null)
            {
                _db.Set<RolePermission>().RemoveRange(list); //批删
            }

            var spid = pid.Split(',');
            List<RolePermission> permissions = new List<RolePermission>();
            spid.ToList().ForEach(x =>
            {
                permissions.Add(new RolePermission() { PermissionId = Convert.ToInt32(x), RoleId = rid });
            });

            //批量添加角色权限
            _db.Set<RolePermission>().AddRange(permissions);

            return _db.SaveChanges(); //SaveChanges()方法是自带事务的

            //int result = 0;
            //_db.Database.ExecuteSqlInterpolated($"delete from RolePermissions where RoleId ={rid}");

            //var spid = pid.Split(',');
            //foreach (var perId in spid)
            //{
            //    result += _db.Database.ExecuteSqlInterpolated($"insert into RolePermissions values({rid},{perId})");
            //}

            //return result;
        }

        /// <summary>
        /// 用sql语句返回所有的角色列表
        /// </summary>
        /// <returns></returns>
        public List<Role> GetRolesFromSql()
        {
            var list = _db.Set<Role>().FromSqlInterpolated($"select * from roles").ToList() ;
            return list;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public int Add(Role role)
        {
            _db.Set<Role>().Add(role);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public int Upt(Role role)
        {
            _db.Entry<Role>(role).State = EntityState.Modified;
            return _db.SaveChanges();
        }
        /// <summary>
        /// 批删
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int Del(string ids)
        {
            string[] arrId = ids.Split(',');
            foreach (var id in arrId)
            {
                _db.Remove(id); 
            }

            return _db.SaveChanges();
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public PageResponseModel<Role> Show(int pageIndex, int pageSize, string name)
        {
            var query = from s in _db.Set<Role>()
                        where (string.IsNullOrEmpty(name) || s.RName.Contains(name))
                        orderby s.RId
                        select s;

            PageResponseModel<Role> page = new PageResponseModel<Role>()
            {
                TotalCount = query.Count(),
                PageList = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()
            };

            return page;
        }
        /// <summary>
        /// 递归方法拼接树
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<PermissionTreeDto> PTree(int pid)
        {
            var list = _db.Set<PermissionTreeDto>().Where(x => x.PId == pid).ToList();
            return list;
        }

        /// <summary>
        /// 获取角色下分配了哪些用户
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public List<UserRole> GetRoleUsers(int rid)
        {
            var list = _db.Set<UserRole>().Where(x => x.RoleId == rid).ToList();
            return list;
        }
    }
}
